<template>
  <base-breadcrumb :title="title" :breadcrumb="!isAudit">
    <!-- 课题注册 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0]">
        <!-- 基础信息 -->
        <a-card :bordered="false" style="margin-bottom: 50px">
          <title-name title="基础信息"></title-name>
          <custom-form
            class="mb20"
            :formList="formList"
            :isEmit="false"
            :form="form"
            :editModel="editModel == 0 ? 'V' : ''"
            @getProjectInfo="getProjectInfo"
            @selectOrg="selectOrg"
          >
            <!-- 小组名称 -->
            <template #topicGroupName>
              <div v-if="editModel == 0" style="margin-top: -3px">{{ form.topicGroupName }}</div>
              <a-auto-complete
                v-else
                v-model="form.topicGroupName"
                :data-source="group"
                placeholder="请输入或选择小组名称"
                :filter-option="filterOption"
                @change="handleChange"
              >
                <a-icon v-if="listLoading" slot="suffixIcon" style="color: #096dd9" type="loading" />
                <a-spin v-if="listLoading" slot="notFoundContent" size="small" />
              </a-auto-complete>
            </template>
            <!-- 培训时间 -->
            <template #trainTime>
              <div v-if="editModel == 0" style="margin-top: -3px">{{ form.trainTime }}h</div>
              <a-row type="flex" v-else>
                <BaseInputNumber style="width: 95%" :precision="0" :min="0" v-model="form.trainTime" />
                <b style="width: 5%" align="right">h</b>
              </a-row>
            </template>
          </custom-form>
          <title-name title="添加课题成员"></title-name>
          <div class="mb12" v-if="editModel != 0">
            <a-button type="primary" icon="plus" @click="$refs['dialogEdit'] && $refs['dialogEdit'].open()"
              >添加人员</a-button
            >
            <a-button class="ml12" :disabled="!selectedRowKeys.length" icon="delete" @click="handleDelete(0)"
              >移除</a-button
            >
          </div>
          <a-table
            rowKey="userId"
            :row-selection="editModel != 0 ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange } : null"
            :dataSource="form.groupMembers"
            :columns="columns"
            :pagination="false"
          >
            <!-- 组内分工 -->
            <template slot="groupTypeId" slot-scope="text, record, index">
              <div v-if="editModel == 0">{{ record.groupTypeName }}</div>
              <template v-else>
                <Selector
                  v-if="index == 0"
                  placeholder="请选择组内分工"
                  :list.sync="options"
                  selectType="46"
                  v-model="record.groupTypeId"
                />
                <a-select v-model="record.groupTypeId" v-else placeholder="请选择组内分工">
                  <a-select-option v-for="item in options" :key="item.id" :value="item.id">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </template>
            </template>
            <!-- 备注 -->
            <template slot="remarks" slot-scope="text, record">
              <div v-if="editModel == 0">{{ text }}</div>
              <BaseInput v-else v-model="record.remarks" />
            </template>
            <!-- 操作栏 -->
            <template slot="actions" slot-scope="text, record, index">
              <a @click="handleDelete(1, { record, index })">移除</a>
            </template>
          </a-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >{{ statusCode === '2' || statusCode === '3' ? '保存' : '保存草稿' }}</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="
            (editModel == 1 && (statusCode === '0' || statusCode === '3')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode === '2')
          "
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail && !isConsultation" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <SelectPerson
      :ref="'dialogEdit'"
      header-title="添加人员"
      :form="{ whether: false }"
      :selectData="form.groupMembers || []"
      @confirm="handleAdd"
      :checkStrictly="true"
    />
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"
    ></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { qcActivityTopicRegister } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import Selector from '@/components/Select/Selector' // 选择器
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople' // 项目人员

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    Selector,
    SelectPerson: () => import('@/components/BComponents/BSelectPerson')
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      listLoading: false, // 列表加载loading
      fetch: false, // 责任书列表加载loading
      editModel: 0, // 0 查看；1 编辑；2 新增
      selectedRowKeys: [], // 选中人员id集合
      selectedRow: [], // 选中人员列表
      statusCode: '', // 审批状态
      form: {
        creatorName: void 0,
        createTime: void 0,
        dept: '技术质量部',
        groupMembers: [],
        viewName: ""
      },
      rules: {
        branchComId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
        topicGroupName: [{ required: true, whitespace: true, message: '请输入或选择小组名称', trigger: 'change' }],
        topicGroupCreationTime: [{ required: true, message: '请选择小组组建日期', trigger: 'change' }],
        topicName: [{ required: true, whitespace: true, message: '请输入课题名称', trigger: 'change' }],
        topicTypeId: [{ required: true, message: '请选择课题类型', trigger: 'change' }],
        trainTime: [{ required: true, message: '请输入质量管理小组人均培训时间', trigger: 'change' }],
        dutyId: [{ required: true, message: '请选择课题负责人', trigger: 'change' }],
        activeYear: [{ required: true, message: '请选择活动开展年度', trigger: 'change' }],
        topicStartTime: [{ required: true, message: '请选择课题活动开始时间', trigger: 'change' }],
        topicEndTime: [{ required: true, message: '请选择课题活动结束时间', trigger: 'change' }],
        guidanceTypeId: [{ required: true, message: '请选择指导者', trigger: 'change' }],
        topicDescribe: [{ required: true, message: '请输入课题描述：（课题立项理由及开展思路）', trigger: 'change' }]
      }, // 表单校验规则
      titles: ['查看课题注册', '编辑课题注册', '新增课题注册'], // 标题
      group: [], // 小组列表
      options: [], // 分工列表
      yearOpen: false, // 年份显隐控件
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted() {
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      qcActivityTopicRegister
        .getDetailById(this.id)
        .then((res) => {
          this.loading[0] = false
          this.statusCode = res.data.statusCode // 审批状态
          res.data.dept = '技术质量部'
          // 小组人员判空
          if (!res.data.groupMembers?.length) {
            res.data.groupMembers = []
          }
          if (!res.data.topicGroupName) {
            delete res.data.topicGroupName
          }
          if (res.code === 200) {
            this.form = res.data
            this.form.viewName = this.form.branchComName + '/' + this.form.projectName
          }
        })
        .catch(() => {
          this.loading[0] = false
        })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_qc_topic_register')
  },
   watch: {
    'form.trainTime'(e){
        e && this.$refs['ruleForm'].clearValidate(['trainTime']);
      },
    'form.topicGroupCreationTime'(e){
        e && this.$refs['ruleForm'].clearValidate(['topicGroupCreationTime']);
      }
  },
  computed: {
    columns() {
      return [
        {
          title: '姓名',
          ellipsis: true,
          dataIndex: 'name'
        },
        {
          title: '职称',
          ellipsis: true,
          dataIndex: 'jobTitle',
          customRender(e) {
            return e || '无'
          }
        },
        {
          title: '岗位',
          ellipsis: true,
          dataIndex: 'postPNames',
          customRender(e) {
            return e || '无'
          }
        },
        {
          title: '学历',
          ellipsis: true,
          dataIndex: 'specialitieMax',
          customRender(e) {
            return e || '无'
          }
        },
        {
          title: '组内分工',
          scopedSlots: { customRender: 'groupTypeId' },
          dataIndex: 'groupTypeId'
        },
        {
          title: '备注',
          scopedSlots: { customRender: 'remarks' },
          dataIndex: 'remarks'
        },
        this.editModel != 0 && {
          title: '操作',
          dataIndex: 'actions',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'actions' }
        }
      ]
    },
    // 表单配置项
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: this.editModel == 0 ? 8 : 16,
          isAutoSelectFirst: true,
          isNeedAuth:true ,
          checkStrictly: true,
          statusSet: [1,2,3,4,5,6],
          disabled: this.editModel == 0,
          isNoBorder: this.editModel == 0,
          viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   viewName: 'branchComName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   viewName: 'projectName',
        //   attrs: {
        //     keyValue: 'branchComId',
        //     autoSelected: this.editModel == 2,
        //     isClear: this.editModel == 2,
        //     isMaintenance: true,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     if (!e?.code) {
        //       return
        //     }
        //     this.$set(this.form, 'projectDeptId', e.projectDeptId)
        //     // 请求小组名称列表
        //     this.listLoading = true
        //     qcActivityTopicRegister
        //       .getGroup(e.code)
        //       .then((res) => {
        //         this.listLoading = false
        //         if (res.code === 200) {
        //           res.data.forEach((item) => {
        //             item.value = item.id
        //             item.text = item.name
        //           })
        //           this.group = res.data || []
        //         }
        //       })
        //       .catch(() => {
        //         this.listLoading = false
        //       })
        //   }
        // },
        {
          keyName: 'topicGroupName',
          slot: true,
          label: '小组名称'
        },
        {
          keyName: 'topicGroupCreationTime',
          type: 'a-date-picker',
          label: '小组组建日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'topicName',
          type: 'BaseInput',
          label: '课题名称'
        },
        {
          type: Selector,
          keyName: 'topicTypeId',
          viewName: 'topicTypeName',
          label: '课题类型',
          attrs: {
            selectType: '47'
          }
        },
        {
          keyName: 'trainTime',
          slot: true,
          label: '质量管理小组人均培训时间'
        },
        {
          keyName: 'dutyId',
          viewName: 'dutyName',
          type: ASelectOrgPeople,
          label: '课题负责人',
          attrs: {
            init: false,
            optionKey: 'id',
            orgId: this.form.projectDeptId
          }
        },
        {
          keyName: 'activeYear',
          type: 'a-date-picker',
          attrs: {
            mode: 'year',
            valueFormat: 'YYYY',
            format: 'YYYY',
            open: this.yearOpen
          },
          label: '活动开展年度',
          change: () => {
            this.yearOpen = true
          },
          openChange: () => {
            this.yearOpen = true
          },
          panelChange: (value) => {
            this.yearOpen = false
            this.$set(this.form, 'activeYear', value.format?.('YYYY'))
            this.$refs['ruleForm'].clearValidate(['activeYear']);
          }
        },
        {
          keyName: 'topicStartTime',
          type: 'a-date-picker',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return this.form.topicEndTime && current && current > this.moment(this.form.topicEndTime).startOf('day')
            }
          },
          label: '课题活动开始时间'
        },
        {
          keyName: 'topicEndTime',
          type: 'a-date-picker',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return (
                this.form.topicStartTime && current && current < this.moment(this.form.topicStartTime).startOf('day')
              )
            }
          },
          label: '课题活动结束时间'
        },
        {
          keyName: 'dept',
          type: 'BaseInput',
          disabled: true,
          label: '质量管理部门'
        },
        {
          keyName: 'lastYearTopic',
          type: 'BaseInput',
          label: '上年度课题'
        },
        {
          type: Selector,
          keyName: 'guidanceTypeId',
          viewName: 'guidanceTypeName',
          label: '指导者',
          attrs: {
            selectType: '48'
          }
        },
        {
          keyName: 'topicDescribe',
          type: 'BaseTextarea',
          label: '课题描述：（课题立项理由及开展思路）',
          span: 24
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
    },
    getProjectInfo(info){
      this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
      // 请求小组名称列表
      this.listLoading = true
      qcActivityTopicRegister
              .getGroup(info.projectId)
              .then((res) => {
                this.listLoading = false
                if (res.code === 200) {
                  res.data.forEach((item) => {
                    item.value = item.id
                    item.text = item.name
                  })
                  this.group = res.data || []
                }
              })
              .catch(() => {
                this.listLoading = false
              })
    },
    /**
     * 小组名称改变
     * @param {String}} e -表单值
     */
    handleChange(e) {
      let topicGroupId = this.group.find((i) => i.id === e)?.id // 小组id
      if (e) {
        // 根据表单值去下拉列表对应，若对应成功，说明是枚举值，进行id和小组日期映射，否则为输入值，则清空id和小组日期
        this.$set(this.form, 'topicGroupName', topicGroupId ? this.group.find((i) => i.id === e)?.name : e)
        this.$set(this.form, 'topicGroupId', topicGroupId || void 0)
        this.$set(
          this.form,
          'topicGroupCreationTime',
          topicGroupId ? this.group.find((i) => i.id === e)?.creationTime : void 0
        )
      }
    },
    /**
     * 表格复选
     * @param {Array}} selectedRowKeys -选中值集合
     */
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    /**
     * 过滤
     * @param {String,Number}} input -表单值
     * @param {Object}} option -业务对象
     */
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
    },
    /**
     * 添加人员
     * @param {Array}} e -选中人员
     */
    handleAdd(e) {
      let groupMembers = e.map((i) => ({
        userId: i.userId,
        name: i.name,
        jobTitle: i.jobTitle,
        postPNames: i.postPNames?.join('，'),
        specialitieMax: i.specialitieMax
      }))
      this.form.groupMembers = groupMembers
    },
    /**
     * 删除行详情
     * @param {Number} type -删除类型：0 选中，1 当前行
     * @param {Object} e -当前行对象
     */
    handleDelete(type, e) {
      this.$confirm({
        title: '温馨提示',
        content: `确定删除${type === 1 ? e.record.name : this.selectedRow?.map((i) => i.name).join('，')}？`,
        onOk: () => {
          if (type === 1) {
            this.form.groupMembers.splice(e.index, 1)
          } else {
            this.form.groupMembers = this.form.groupMembers.filter((i) => !this.selectedRowKeys.includes(i.userId))
            this.selectedRow = []
            this.selectedRowKeys = []
          }
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      that.setProcessConfig = null;
      let name = ['updatePost', 'handleCreate'][that.editModel - 1]
      const submit = () => {
        // 提交表单
        that.loading[statusCode] = true
        let form = that.$clone(that.form)
        form.statusCode = that.statusCode == '3' && statusCode == 0 ? that.statusCode : statusCode
        return qcActivityTopicRegister[name](form)
          .then((res) => {
            that.loading[statusCode] = false
            if (res.code === 200 || res.data.code === 200) {
              that.$message.success(['保存', '提交'][statusCode] + '成功！')
               if(statusCode*1===1) {
               //提交时，返回id
                  that.businessId = res.data.id;
                  that.setProcessConfig = this.processConfig;
                  return
              }else{
                that.$multiTab.close()
                }
            }
          })
          .catch(() => {
            that.loading[statusCode] = false
          })
      }
      // 若是草稿则无需校验表单
      if (statusCode === 0) {
        submit()
        return
      }
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 校验人员
          if (that.form.groupMembers?.length) {
            for (let index in that.form.groupMembers) {
              let item = that.form.groupMembers[index]
              // 校验组内分工
              if (!item.groupTypeId) {
                that.$message.warning(`第${Number(index) + 1}行组内分工不能为空！`)
                return
              }
            }
          } else {
            that.$message.warning('人员列表不能为空！')
            return
          }
          this.submitApprovalConfirm(this.processConfig, (flag)=>{
            if(!flag) {
              return
            }
            submit()
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-calendar-picker {
  width: 100% !important;
}
</style>
